<?php

namespace yan\backendclient\modules\backendmodule\models;

use Yii;

/**
 * This is the model class for table "{{%backend_module_sql}}".
 *
 * @property integer $id
 * @property string $module_id
 * @property string $targetClass
 * @property integer $created_at
 * @property integer $updated_at
 */
class Gii extends \yii\base\Model
{
    const TYPE_MODEL = 'model';
    const TYPE_CURD = 'curd';
    public $table_name;
    public $controller_id;
    public $use_curd;
    public $module_id;
    public $type;
    public $modelClass;
    private $_generate;
    public function rules()
    {
        return [
            [['type','module_id'], 'required'],
            [['table_name'], 'required', 'on'=>self::TYPE_MODEL],
            [['modelClass'], 'required', 'on'=>self::TYPE_CURD],
            [['use_curd'], 'integer'],
            [['table_name', 'modelClass'], 'validateType'],
            [['table_name', 'controller_id', 'type'], 'string', 'max' => 100],
        ];
    }
    public function validateType(){
        if($this->type==self::TYPE_MODEL){
            if(empty($this->table_name)){
                $this->addError('table_name', '不能為空');
            }
        }else if($this->type==self::TYPE_CURD){
            if(empty($this->modelClass)){
                $this->addError('modelClass', '不能為空');
            }
        }
    }
    public function getGenerate(){
        return $this->_generate;
    }
    public function generate($type='model'){
        if($type=='model'){
            $modelGenerate = new \yii\gii\generators\model\Generator();
            $modelGenerate->tableName = $this->table_name;
            $modelGenerate->modelClass = $this->tableNameToModelClass();
            $modelGenerate->ns = $this->getNamespaceOfClass('models');
            $files = $modelGenerate->generate();
            $this->_generate = $modelGenerate;
        }else if($type=='curd'){
            $curdGenerate = new \yan\backendclient\modules\backendmodule\generators\laycurd\Generator();
            $modelsClasses = explode('\\', $this->modelClass);
            $modelClassName = end($modelsClasses);
            $curdGenerate->modelClass = $this->modelClass;
            $curdGenerate->serviceClass = $this->getServiceId($modelClassName);
            $curdGenerate->formClass = $this->getFormId($modelClassName);
            $curdGenerate->searchModelClass = $this->getSearchId($modelClassName);
            $curdGenerate->controllerClass = $this->getControllerId();
            $curdGenerate->viewPath = $this->getModuleViewPath();
            $curdGenerate->baseControllerClass = 'backend\components\controllers\CController';

            $files = $curdGenerate->generate();
            $this->_generate = $curdGenerate;
        }
        return $files;
    }
    public function tableNameToModelClass(){
        $table_name = str_replace(Yii::$app->db->tablePrefix, '', $this->table_name);
        $table_names = explode('_', $table_name);
        foreach ($table_names as $key => &$value) {
            $value = ucfirst($value);
        }
        $modelClass = implode('', $table_names);
        return $modelClass;
    }
    public function getNamespaceOfClass($last_path) {
        $module = Yii::$app->getModule($this->module_id);
        $reflection = new \ReflectionClass($module);
        $namespace = $reflection->getNamespaceName();
        $namespace = $namespace . '\\'.$last_path;
        return $namespace;
    }
    public function getControllerId(){
        $ns = $this->getNamespaceOfClass('controllers');
        $this->controller_id = !empty($this->controller_id) ? $this->controller_id : 'default';
        $ids = explode('-', $this->controller_id);
        foreach ($ids as $key => &$val) {
            $val = ucfirst($val);
        }
        $controller_id = implode('', $ids) . 'Controller';
        return $ns . '\\'.$controller_id;
    }
    public function getServiceId($modelClass){
        $ns = $this->getNamespaceOfClass('service');
        return $ns . '\\' .$modelClass .'Service';
    }
    public function getFormId($modelClass){
        $ns = $this->getNamespaceOfClass('forms');
        return $ns . '\\' .$modelClass .'Form';
    }
    public function getSearchId($modelClass){
        $ns = $this->getNamespaceOfClass('forms');
        return $ns . '\\' .$modelClass .'Search';
    }
    public function getModuleViewPath(){
        // $ns = $this->getNamespaceOfClass('views');
        // $path = str_replace('\\', '/', $ns);
        $path = 'modules/'.$this->module_id.'/views';
        $this->controller_id = !empty($this->controller_id) ? $this->controller_id : 'default';
        return $path . '/'.$this->controller_id;
    }
    public function getClassModelList(){
        $ns = $this->getNamespaceOfClass('models');
        $path = str_replace('\\', '/', $ns);
        $path = Yii::getAlias('@root'). '/'.$path;
        $files = scandir($path);
        $list = [];
        foreach ($files as $file) {
            if ($file != '.' && $file != '..') {
                $file = str_replace('.php', '', $file);
                $className = $ns .'\\'. $file;
                $list[$className] = $className;
            }
        }
        return $list;
    }
}
